package com.fulu.javabase.arithmetic;

public class TwoNumberSum {
    /**
     * Definition for singly-linked list.
     * */
    public static class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    static class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode lr = new ListNode();
            ListNode lcr = lr;
            do {
                int sum = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) +  + lr.val;
                if(sum >= 10){
                    lr.next = new ListNode(1);
                    sum = sum - 10;
                }
                lr.val = sum;
                l1 = l1 == null ? null : l1.next;
                l2 = l2 == null ? null : l2.next;
                // l1 or l2 not finished, and lr.next is null
                boolean nextFlag = (l1 != null || l2 != null) && lr.next == null;
                lr.next = nextFlag ? new ListNode() : lr.next;
                lr = lr.next;
            } while (l1 != null || l2 != null);
            return lcr;
        }
    }

    public static void main(String[] args) {
        //[2,4,3]
        //[5,6,4]
        ListNode l1 = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9)))))));
        ListNode l2 = new ListNode(9, new ListNode(9, new ListNode(9)));
        ListNode listNode = new Solution().addTwoNumbers(l1, l2);
        do {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }while (listNode != null);
    }

}
